/*   Shotscreens
 *   Copyright (C) 2010, Vadim Zakondyrin (http://crystalnix.com)
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <authdialog.h>
#include "applicationwindowitem.h"
#include "fullscreenwidget.h"
#include "settings.h"
#include "shotscreens.h"

#include "Editor/screenshotseditor.h"
#include "Interfaces/settingsmenu.h"
#include "Interfaces/tray.h"
#include "../pluginSDK/UploaderInterface.h"

#include <QApplication>
#include <QDesktopWidget>
#include <QGraphicsScene>
#include <QPluginLoader>
#include <QTcpServer>

#include <QDebug>

ShotScreens::ShotScreens(QWidget *parent)
    : QDialog(parent), shortcut(this), active(false)
{
    initializationTray();
    changeActivity();    
}

ShotScreens::~ShotScreens()
{
    if(srv)
    {
        delete srv;
    }
    if(fullscreenwidget)
    {
        delete fullscreenwidget;
    }

}

void ShotScreens::SetShortcutKey()
{
    shortcut.setShortcut(Settings::instance().getKey());
}

bool ShotScreens::IsRunned()
{
    srv=new QTcpServer();

    if(srv->listen(QHostAddress::Any,46462)==false)
    {
        return false;
    }
    else return true;
}

//void ShotScreens::GetAllWindowsToList()
// I think we should get this functionality through platform native API functions
// as we do with globalshortcut. Anyway qxtlib code will be helpful in this task.

void ShotScreens::takeScreenshot() {
    QPixmap screenOfDesktop; // it's better to move it to header
    screenOfDesktop = QPixmap(); // clear image for low memory situations
                                 // on embedded devices.
                                 // (See Qt Desktop->Screenshot example).
    screenOfDesktop = QPixmap::grabWindow(QApplication::desktop()->screen()->winId());

    fullscreenwidget = new FullscreenWidget(screenOfDesktop); // as an option we can pass shotscreens object as a parent of fullscreenwidget.
    fullscreenwidget->raise();
    fullscreenwidget->activateWindow(); // nessesary to change cursor. if we do not do it, cursor will be an arrow.

    fullscreenwidget->showNormal();

    connect(fullscreenwidget, SIGNAL(pixmapSended(QPixmap)), this, SLOT(startEditor(QPixmap))); // bad case. shotscreens have to manage it and fullscreens widget shouldn't connect to editor.
    connect(qApp, SIGNAL(aboutToQuit()), fullscreenwidget, SLOT(close()));
}

void ShotScreens::uploadData(QByteArray data)
{
    if (data.isNull())
        return;
    QPluginLoader pl;
    QString str;
    QString plugin_name;

    plugin_name = Settings::instance().getPluginName();

    if(plugin_name.length()<1)
    {
        MessageBox.setModal(true);
        MessageBox.information(NULL, QString(""), QString("No plugin was selected!"), QMessageBox::Ok, QMessageBox::NoButton);
        return;
    }

    str=str.append(QApplication::applicationDirPath());
    str=str.append("/plugins/");
    str=str.append(plugin_name);
    pl.setFileName(str);
    QObject *tmp = pl.instance();

    UploaderInterface * ui = qobject_cast<UploaderInterface *>(tmp);
    ui->SetLoginAndPassword(QString(""),QString(""));
    ui->UploadStream(data);
}

void ShotScreens::initializationTray()
{
    connect(tray.activityAction, SIGNAL(triggered()), this, SLOT(changeActivity()));
    connect(tray.settingsAction, SIGNAL(triggered()), this, SLOT(openSettingsMenu())); // new settings menu
    connect(tray.quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
    connect(tray.captureAction, SIGNAL(triggered()), this, SLOT(takeScreenshot())); // new capture
    connect(tray.change_account, SIGNAL(triggered()), this, SLOT(ChangeAccount()));
}

void ShotScreens::showTray()
{

    QString icon_path;
    icon_path=icon_path.append(QApplication::applicationDirPath()); //???
    icon_path=icon_path.append("/images/black.ico");
    tray.setIcon(QIcon(":/images/black.ico"));
    tray.show();
}

void ShotScreens::hideTray()
{
    tray.hide();
}

void ShotScreens::ChangeAccount()
{
    Settings::instance().setLogin("");
    Settings::instance().setPassword("");

    AuthDialog *dialog = new AuthDialog(this);

    dialog->setAttribute(Qt::WA_DeleteOnClose);
    dialog->SetTrayHandle(this);
    dialog->OnLoad();
    dialog->setModal(true);
    dialog->show();
}

void ShotScreens::startEditor(QPixmap background)
{

    fullscreenwidget->close(); // now we want see the not the selecting widget but editor

    screenshotsEditor = new ScreenShotsEditor(background);

    screenshotsEditor->setAttribute(Qt::WA_DeleteOnClose);
    connect(qApp, SIGNAL(aboutToQuit()), screenshotsEditor, SLOT(close()));
    screenshotsEditor->show();
    screenshotsEditor->activateWindow();
}

void ShotScreens::changeHotkey(QKeySequence key) {
    Settings::instance().setKey(key);
    SetShortcutKey();
}

void ShotScreens::changeActivity() {
    if(active) {
        active = false;
        disconnect(&shortcut, SIGNAL(activated()), this, SLOT(takeScreenshot()));
        tray.shotingStoped();
    }
    else {
        active = true;
        connect(&shortcut, SIGNAL(activated()), this, SLOT(takeScreenshot()));
        tray.shotingStarted();
    }
}

void ShotScreens::openSettingsMenu() {
    settingsMenu = new SettingsMenu;
    settingsMenu->setAttribute(Qt::WA_DeleteOnClose);

    connect(qApp, SIGNAL(aboutToQuit()), settingsMenu, SLOT(close()));
    connect(settingsMenu, SIGNAL(hotkeyLineEditHasBeenChanged(QKeySequence)), SLOT(changeHotkey(QKeySequence)));

    settingsMenu->setWindowTitle(tr("Settings"));
    settingsMenu->setKey(Settings::instance().getKey());
    settingsMenu->show();    
}
